package com.relytosoft.mizar.media.analyze.services.service.behavior.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.relytosoft.dubhe.common.core.base.page.PageQuery;
import com.relytosoft.dubhe.common.core.exception.ServiceException;
import com.relytosoft.dubhe.common.core.utils.BeanCopyUtils;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.dubhe.common.satoken.entity.CurrentUser;
import com.relytosoft.mizar.media.analyze.api.entity.behavior.AyBehaviorTask;
import com.relytosoft.mizar.media.analyze.api.entity.behavior.AyBehaviorTaskSon;
import com.relytosoft.mizar.media.analyze.api.entity.system.AyPlanTemplate;
import com.relytosoft.mizar.media.analyze.api.pojo.dto.AyBehaviorTaskDto;
import com.relytosoft.mizar.media.analyze.api.pojo.dto.AyBehaviorTaskPlanDto;
import com.relytosoft.mizar.media.analyze.api.pojo.dto.AyBehaviorTaskSonDto;
import com.relytosoft.mizar.media.analyze.api.pojo.dto.AyTaskIdDto;
import com.relytosoft.mizar.media.analyze.api.pojo.query.AyBehaviorTaskSonQuery;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyBatchVo;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyBehaviorTaskPlanVo;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyBehaviorTaskSonVo;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyCameraVo;
import com.relytosoft.mizar.media.analyze.services.mapper.behavior.AyBehaviorTaskMapper;
import com.relytosoft.mizar.media.analyze.services.mapper.behavior.AyBehaviorTaskSonMapper;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyBehaviorTaskSonService;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyLaneWithRegionService;
import com.relytosoft.mizar.media.analyze.services.service.system.AyPlanTemplateService;
import com.relytosoft.mizar.media.common.config.properties.MizarAnalyzeProperties;
import com.relytosoft.mizar.media.common.constant.AyCacheConstants;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import com.relytosoft.mizar.media.common.emqx.client.MqttOp;
import com.relytosoft.mizar.media.common.enums.DeleteStatusEnum;
import com.relytosoft.mizar.media.common.enums.TaskStatusEnum;
import com.relytosoft.mizar.media.common.enums.TaskTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lj
 * @date 2022/6/7 10:17
 */
@Service
public class AyBehaviorTaskSonServiceImpl extends ServiceImpl<AyBehaviorTaskSonMapper, AyBehaviorTaskSon> implements AyBehaviorTaskSonService {

    @Resource
    private AyBehaviorTaskMapper ayBehaviorTaskMapper;


    @Resource
    private MizarAnalyzeProperties analyzeProperties;


    @Resource
    private AyPlanTemplateService ayPlanTemplateService;

    @Resource
    private AyLaneWithRegionService ayLaneWithRegionService;


    @Override
    public IPage<AyBehaviorTaskSonVo> selectAyBehaviorTaskSonPageList(PageQuery pageQuery, AyBehaviorTaskSonQuery ayBehaviorTaskSonQuery) {
        if (StrUtil.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        return this.baseMapper.selectPageSonList(pageQuery.build(), ayBehaviorTaskSonQuery);
    }

    @Override
    public boolean deleteByMainTaskId(List<Integer> behaviorTaskIds) {
        //1. 构造查询条件，运行中及创建中的任务不允许删除
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        wrapper
                .in(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskIds)
                .notIn(AyBehaviorTaskSon::getStatus, TaskStatusEnum.RUNING.getValue(), TaskStatusEnum.CREATED.getValue())
                .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue());
        //2. 构建删除条件
        AyBehaviorTaskSon ayBehaviorTaskSon = new AyBehaviorTaskSon();
        ayBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.DELETED.getValue());
        ayBehaviorTaskSon.setUpdatedBy(CurrentUser.getCurrentUserFullName());
        ayBehaviorTaskSon.setUpdatedId(CurrentUser.getCurrentUserId());
        //3. 执行删除
        return this.update(ayBehaviorTaskSon, wrapper);
    }

    @Override
    public boolean deleteAndInsertTaskSons(List<AyBehaviorTaskSon> deleteTaskSons, List<AyBehaviorTaskSon> insertTaskSons, Integer behaviorTaskId) {
        boolean result = false;
        if (behaviorTaskId != null && behaviorTaskId > 0) {
            //已停止，未删除的子任务需要删除，再新增，再启动
            //1. 构造查询条件
            LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
            wrapper.eq(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskId)
                    .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                    .eq(AyBehaviorTaskSon::getStatus, TaskStatusEnum.FINISHED.getValue());

            //2. 构建删除条件
            AyBehaviorTaskSon ayBehaviorTaskSon = new AyBehaviorTaskSon();
            ayBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.DELETED.getValue());
            ayBehaviorTaskSon.setUpdatedBy(CurrentUser.getCurrentUserFullName());
            ayBehaviorTaskSon.setUpdatedId(CurrentUser.getCurrentUserId());

            //3. 执行删除
            result = this.update(ayBehaviorTaskSon, wrapper);
        } else if (deleteTaskSons != null && deleteTaskSons.size() > 0) {
            result = this.updateBatchById(deleteTaskSons);
        }
        //4. 执行新增
        if (result) {
            result = this.saveBatch(insertTaskSons);
        }
        //5. 判断result是否成功,如果成功，则返回，失败则抛出异常
        if (!result) {
            throw new RuntimeException("删除子任务失败");
        }
        return true;
    }

    @Override
    public boolean updateNeedStartTaskSons(List<AyBehaviorTaskSon> startTaskSons, Integer behaviorTaskId) {
        //1. 构造查询条件
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        //2. 判断behaviorTaskId
        if (behaviorTaskId != null && behaviorTaskId > 0) {
            wrapper.eq(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskId);
        } else {
            //3. 获取startTaskSons的id
            List<Integer> ids = startTaskSons.stream().map(AyBehaviorTaskSon::getId).collect(Collectors.toList());
            wrapper.in(AyBehaviorTaskSon::getId, ids);
        }
        wrapper
                .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .in(AyBehaviorTaskSon::getStatus, TaskStatusEnum.UNUSUAL.getValue(), TaskStatusEnum.NOT_STARTED.getValue());

        //4. 构建更新条件
        AyBehaviorTaskSon ayBehaviorTaskSon = new AyBehaviorTaskSon();
        ayBehaviorTaskSon.setStatus(TaskStatusEnum.CREATED.getValue());
        ayBehaviorTaskSon.setUpdatedBy(CurrentUser.getCurrentUserFullName());
        ayBehaviorTaskSon.setUpdatedId(CurrentUser.getCurrentUserId());
        ayBehaviorTaskSon.setBeginTime(LocalDateTime.now());
        ayBehaviorTaskSon.setEndTime(null);
        //5. 执行更新
        return this.update(ayBehaviorTaskSon, wrapper);
    }

    @Override
    public boolean stopSonTask(List<AyBehaviorTaskSon> stopTaskSons, Integer behaviorTaskId) {
        //1. 判断behaviorTaskId
        if (behaviorTaskId != null && behaviorTaskId > 0) {
            //2. 构造查询条件，运行中的子任务可停止
            LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
            wrapper
                    .eq(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskId)
                    .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                    .in(AyBehaviorTaskSon::getStatus, TaskStatusEnum.RUNING.getValue());
            //3. 构建更新条件
            AyBehaviorTaskSon ayBehaviorTaskSon = new AyBehaviorTaskSon();
            ayBehaviorTaskSon.setStatus(TaskStatusEnum.FINISHED.getValue());
            ayBehaviorTaskSon.setUpdatedBy(CurrentUser.getCurrentUserFullName());
            ayBehaviorTaskSon.setUpdatedId(CurrentUser.getCurrentUserId());
            ayBehaviorTaskSon.setEndTime(LocalDateTime.now());
            //4. 执行更新
            return this.update(ayBehaviorTaskSon, wrapper);
        } else if (stopTaskSons != null && stopTaskSons.size() > 0) {
            //5. 执行更新
            return this.updateBatchById(stopTaskSons);
        }
        return false;
    }


    @Override
    public AyBatchVo insertAyBehaviorTaskSon(AyBehaviorTaskSonDto ayBehaviorTaskSonDto, List<AyBehaviorTaskSon> ayBehaviorTaskSonArrayList) {
        //获取getAyCameraVos
        List<AyCameraVo> ayCameraVos = ayBehaviorTaskSonDto.getAyCameraVos();
        //遍历ayCameraVos，获取对象AyCameraVo并验证属性cameraId，cameraName和videoUrl不为空,不为空串，也不为“ ”
        for (AyCameraVo ayCameraVo : ayCameraVos) {
            if (StringUtils.isBlank(ayCameraVo.getCameraId())
                    || StringUtils.isBlank(ayCameraVo.getCameraName())
                    || StringUtils.isBlank(ayCameraVo.getVideoUrl())) {
                throw new RuntimeException("cameraId,cameraName,videoUrl不能为空");
            }
        }
        //根据behaviorTaskId查询AyBehaviorTask
        AyBehaviorTask ayBehaviorTask = ayBehaviorTaskMapper.selectById(ayBehaviorTaskSonDto.getBehaviorTaskId());
        //如果为null或是已删除，则抛出异常
        if (ayBehaviorTask == null || ayBehaviorTask.getDeleted() == DeleteStatusEnum.DELETED.getValue()) {
            throw new RuntimeException("查询不到该任务");
        }
        //赋值
        ayBehaviorTask.setAyCameraVos(ayCameraVos);
        AyBehaviorTaskDto ayBehaviorTaskDto = BeanCopyUtils.copy(ayBehaviorTask, AyBehaviorTaskDto.class);
        AyBatchVo ayBatchVo = new AyBatchVo();
        ayBatchVo.setTotal(ayCameraVos.size());
        // 添加任务前参数校验
        if (addFrontVerify(ayBehaviorTaskDto)) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ayCameraVos.size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合创建条件的设备"));
            throw new ServiceException(JSONObject.toJSONString(ayBatchVo));
        }

        ayCameraVos.forEach(item -> {
            AyBehaviorTaskSon ayBehaviorTaskSon = new AyBehaviorTaskSon();
            ayBehaviorTaskSon.setBehaviorTaskId(ayBehaviorTask.getId());
            ayBehaviorTaskSon.setCameraId(item.getCameraId());
            ayBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.NOT_DELETED.getValue());
            ayBehaviorTaskSon.setCameraName(item.getCameraName());
            ayBehaviorTaskSon.setVideoUrl(item.getVideoUrl());
            ayBehaviorTaskSon.setLicenceUsing(0);
            ayBehaviorTaskSon.setBehavior(0);
            ayBehaviorTaskSon.setProgress(0);
            ayBehaviorTaskSon.setAlgorithmid(ayBehaviorTask.getAlgorithmid());
            ayBehaviorTaskSon.setSubtypes(ayBehaviorTask.getSubtypes());
            ayBehaviorTaskSon.setStatus(TaskStatusEnum.RUNING.getValue());
            ayBehaviorTaskSon.setBeginTime(LocalDateTime.now());
            ayBehaviorTaskSon.setType(TaskTypeEnum.REAL_TIME.getValue());
            ayBehaviorTaskSon.setIsSearchStatus(0);
            ayBehaviorTaskSonArrayList.add(ayBehaviorTaskSon);
        });
        boolean insert = this.saveBatch(ayBehaviorTaskSonArrayList);
        //如果插入成功
        if (insert) {
            ayBatchVo.setSuccess(ayBehaviorTaskSonArrayList.size());
            ayBatchVo.setError(ayCameraVos.size() - ayBehaviorTaskSonArrayList.size());
        }
        return ayBatchVo;
    }

    @Override
    public boolean deleteAyBehaviorTaskSon(List<Integer> ids) {
        //运行中，创建中，的任务不允许删除
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        wrapper
                .in(AyBehaviorTaskSon::getId, ids)
                .notIn(AyBehaviorTaskSon::getStatus, TaskStatusEnum.RUNING.getValue(), TaskStatusEnum.CREATED.getValue());
        //更新状态为删除
        AyBehaviorTaskSon ayBehaviorTaskSon = new AyBehaviorTaskSon();
        ayBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.DELETED.getValue());
        ayBehaviorTaskSon.setUpdatedBy(CurrentUser.getCurrentUserFullName());
        ayBehaviorTaskSon.setUpdatedId(CurrentUser.getCurrentUserId());
        return this.update(ayBehaviorTaskSon, wrapper);
    }

    @Override
    public List<AyBehaviorTaskSon> canStartAyBehaviorTaskSon(AyTaskIdDto ayTaskIdDto, AyBatchVo ayBatchVo) {
        if (ayTaskIdDto.getIds().isEmpty()) {
            throw new ServiceException("请选择需要启动的子任务！");
        }
        if (ayTaskIdDto.getParentId() == null || ayTaskIdDto.getParentId() <= 0) {
            throw new ServiceException("主任务ID不能为空！");
        }
        ayBatchVo.setTotal(ayTaskIdDto.getIds().size());
        //构造查询条件
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        wrapper
                .eq(AyBehaviorTaskSon::getBehaviorTaskId, ayTaskIdDto.getParentId())
                .in(AyBehaviorTaskSon::getId, ayTaskIdDto.getIds())
                .in(AyBehaviorTaskSon::getStatus, TaskStatusEnum.FINISHED.getValue(), TaskStatusEnum.NOT_STARTED.getValue(), TaskStatusEnum.UNUSUAL.getValue())
                .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue());
        //查询符合条件的子任务
        List<AyBehaviorTaskSon> ayBehaviorTaskSonList = this.list(wrapper);
        if (ayBehaviorTaskSonList.isEmpty()) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ayTaskIdDto.getIds().size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合条件的子任务"));
            throw new ServiceException(JSONObject.toJSONString(ayBatchVo));
        }
        return ayBehaviorTaskSonList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startTask(List<AyBehaviorTaskSon> insertTaskSons, List<AyBehaviorTaskSon> startTaskSons,
                          List<AyBehaviorTaskSon> currentTaskSons, AyBatchVo ayBatchVo) {
        List<AyBehaviorTaskSon> deleteTaskSons = new ArrayList<>();
        buildNeedInsertAndDeleteTaskSons(currentTaskSons, deleteTaskSons, insertTaskSons);
        buildStartTaskSons(currentTaskSons, startTaskSons);
        //成功计数和失败计数
        int success = 0;
        int error = 0;
        //是否成功
        boolean isSuccess;
        //如果deleteTaskSons不为空，则删除
        if (!deleteTaskSons.isEmpty()) {
            isSuccess = deleteAndInsertTaskSons(deleteTaskSons, insertTaskSons, null);
            if (isSuccess) {
                success += deleteTaskSons.size();
            } else {
                error += deleteTaskSons.size();
            }
        }
        //如果startTaskSons不为空，则更新状态为运行中
        if (!startTaskSons.isEmpty()) {
            isSuccess = updateNeedStartTaskSons(startTaskSons, null);
            if (isSuccess) {
                success += startTaskSons.size();
            } else {
                error += startTaskSons.size();
            }
        }
        //如果success和error都为0，则说明没有任务可以启动
        if (success == 0 && error == 0) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(0);
            ayBatchVo.setErrorMsg(Collections.singletonList("没有任务可以启动"));
        } else {
            ayBatchVo.setSuccess(success);
            ayBatchVo.setError(error);
        }
    }

    @Override
    public List<AyBehaviorTaskSon> canStopAyBehaviorTaskSon(AyTaskIdDto taskIdDto, AyBatchVo ayBatchVo) {
        //参数校验
        if (taskIdDto.getIds().isEmpty()) {
            throw new ServiceException("请选择需要停止的子任务！");
        }
        if (taskIdDto.getParentId() == null || taskIdDto.getParentId() <= 0) {
            throw new ServiceException("主任务ID不能为空！");
        }
        ayBatchVo.setTotal(taskIdDto.getIds().size());
        //构造查询条件，未删除，运行中、创建中（更新时间已过配置）的子任务
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        wrapper
                .in(AyBehaviorTaskSon::getId, taskIdDto.getIds())
                .eq(AyBehaviorTaskSon::getBehaviorTaskId, taskIdDto.getParentId())
                .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .and(item -> item
                        .eq(AyBehaviorTaskSon::getStatus, TaskStatusEnum.RUNING.getValue())
                        .or(item2 -> item2
                                .eq(AyBehaviorTaskSon::getStatus, TaskStatusEnum.CREATED.getValue())
                                .lt(AyBehaviorTaskSon::getUpdatedTime, LocalDateTime.now().plusSeconds(-1L * analyzeProperties.getTaskCanStopTime()))));
        //查询符合条件的子任务
        List<AyBehaviorTaskSon> ayBehaviorTaskSonList = this.list(wrapper);
        if (ayBehaviorTaskSonList.isEmpty()) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(taskIdDto.getIds().size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合条件的子任务"));
            throw new ServiceException(JSONObject.toJSONString(ayBatchVo));
        }
        return ayBehaviorTaskSonList;
    }

    @Override
    public boolean stop(List<AyBehaviorTaskSon> stopTaskSons, List<AyBehaviorTaskSon> ayBehaviorTaskSonArrayList,
                        AyBatchVo ayBatchVo) {
        //构造需要停止的子任务
        buildStopTaskSons(ayBehaviorTaskSonArrayList, stopTaskSons);
        //停止子任务
        boolean isSuccess = stopSonTask(stopTaskSons, null);
        if (isSuccess) {
            ayBatchVo.setSuccess(stopTaskSons.size());
            ayBatchVo.setError(ayBatchVo.getTotal() - stopTaskSons.size());
        } else {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ayBatchVo.getTotal());
            ayBatchVo.setErrorMsg(Collections.singletonList("子任务停止失败"));
        }
        return isSuccess;
    }

    @Override
    public void sendMessage(AyBehaviorTaskSon ayBehaviorTaskSon) {
        //获取区域参数,根据设备cameraId和subtypes获取区域参数
        JSONArray jsonArray = ayLaneWithRegionService
                .getByCameraIdAndAlgorithmIdAndSubType(ayBehaviorTaskSon.getCameraId(),
                        ayBehaviorTaskSon.getSubtypes());
        //构造消息
        JSONObject message = getRequestInfo(jsonArray, ayBehaviorTaskSon);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OpType", "INSERT_BEHAVIOR_TASK");
        jsonObject.put("Data", message.toJSONString());
        //发送消息
        MqttOp.publish(MediaMqConstants.BEHAVIOR_TASK_TOPIC, jsonObject.toJSONString());
    }

    private JSONObject getRequestInfo(JSONArray jsonArray, AyBehaviorTaskSon ayBehaviorTaskSon) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("TaskType", ayBehaviorTaskSon.getType());
        JSONObject behaviorAnalysis = new JSONObject();
        behaviorAnalysis.put("ApplicationScenarios", ayBehaviorTaskSon.getAlgorithmid());
        JSONArray subTypes = new JSONArray();
        subTypes.add(ayBehaviorTaskSon.getSubtypes());
        behaviorAnalysis.put("SubTypes", subTypes);
        jsonObject.put("BehaviorAnalysis", behaviorAnalysis);
        JSONObject inputSrc = new JSONObject();
        inputSrc.put("SrcID", ayBehaviorTaskSon.getCameraId());
        inputSrc.put("SrcType", 1);
        JSONObject rtspSrc = new JSONObject();
        rtspSrc.put("Address", ayBehaviorTaskSon.getVideoUrl());
        inputSrc.put("RtspSrc", rtspSrc);
        JSONObject gb28181RealSrc = new JSONObject();
        gb28181RealSrc.put("ClientGBCode", null);
        gb28181RealSrc.put("ProtocolType", null);
        gb28181RealSrc.put("SipServerGBCode", null);
        gb28181RealSrc.put("SipServerGBPW", null);
        gb28181RealSrc.put("SipServerIP", null);
        gb28181RealSrc.put("SipServerPort", null);
        inputSrc.put("GB28181RealSrc", gb28181RealSrc);
        jsonObject.put("InputSrc", inputSrc);

        JSONObject algParam = new JSONObject();
        JSONObject detRec = new JSONObject();
        JSONObject detect = new JSONObject();
        JSONObject detectRegion = new JSONObject();
        detectRegion.put("RegionType", 0);
        detectRegion.put("HotRegionList", jsonArray);
        detect.put("DetectRegion", detectRegion);
        detRec.put("Detect", detect);
        algParam.put("DetRec", detRec);
        jsonObject.put("AlgParam", algParam);
        jsonObject.put("UploadUrl", "");
        jsonObject.put("StatusUploadUrl", "");
        System.out.println(jsonObject.toJSONString());
        return jsonObject;
    }


    @Override
    public boolean sonTaskAddPlan(AyBehaviorTaskPlanDto ayBehaviorTaskPlanDto) {
        if (ayBehaviorTaskPlanDto.getIds().isEmpty()) {
            throw new ServiceException("请选择需要添加计划的子任务！");
        }
        //查询子任务信息
        List<AyBehaviorTaskSon> ayBehaviorTaskSonList = this.listByIds(ayBehaviorTaskPlanDto.getIds());
        //判断子任务是否存在
        if (ayBehaviorTaskSonList.isEmpty()) {
            throw new ServiceException("子任务不存在！");
        }
        //筛选出未删除的子任务
        ayBehaviorTaskSonList.removeIf(item -> item.getIsDeleted() == DeleteStatusEnum.DELETED.getValue());
        //判断计划模板planTemplateId是否存在
        if (ayBehaviorTaskPlanDto.getPlanTemplateId() != null) {
            //查询计划模板信息
            AyPlanTemplate ayPlanTemplate = ayPlanTemplateService.getById(ayBehaviorTaskPlanDto.getPlanTemplateId());
            //判断计划模板是否存在
            if (ayPlanTemplate == null) {
                throw new ServiceException("计划模板不存在");
            }
            //设置计划信息到子任务
            ayBehaviorTaskSonList.forEach(ayBehaviorTaskSon -> {
                ayBehaviorTaskSon.setPlanInfoNum(ayPlanTemplate.getPlanInfoNum());
                ayBehaviorTaskSon.setPlanType(ayPlanTemplate.getPlanType());
                ayBehaviorTaskSon.setPlanInfoList(ayPlanTemplate.getPlanInfoList());
            });
        } else {
            ayBehaviorTaskSonList.forEach(ayBehaviorTaskSon -> {
                //直接设置计划信息到子任务
                ayBehaviorTaskSon.setPlanInfoNum(ayBehaviorTaskPlanDto.getPlanInfoNum());
                ayBehaviorTaskSon.setPlanType(ayBehaviorTaskPlanDto.getPlanType());
                ayBehaviorTaskSon.setPlanInfoList(ayBehaviorTaskPlanDto.getPlanInfoList());
            });
        }
        //批量更新子任务信息
        boolean isSuccess = this.updateBatchById(ayBehaviorTaskSonList);
        if (isSuccess) {
            //更新redis数据
            ayBehaviorTaskSonList.forEach(ayBehaviorTaskSon -> updateRedisInfo(
                    ayBehaviorTaskSon.getTaskId(),
                    ayBehaviorTaskSon.getPlanType(),
                    ayBehaviorTaskSon.getPlanInfoNum(),
                    ayBehaviorTaskSon.getPlanInfoList()));
        }
        return isSuccess;
    }

    private void updateRedisInfo(String taskId, Integer planType, Integer planInfoNum, String planInfoList) {
        //判断布控任务ID不为空，添加到redis
        if (taskId != null) {
            //查询redis数据，并更新
            String faceDispositionInfo = (String) RedisUtil.get(AyCacheConstants.AY_BEHAVIOR_ANALYZE + taskId);
            JSONObject jsonObject = JSONObject.parseObject(faceDispositionInfo);
            jsonObject.put("planInfoList", planType);
            jsonObject.put("planType", planInfoNum);
            jsonObject.put("planInfoNum", planInfoList);
            RedisUtil.set(AyCacheConstants.AY_BEHAVIOR_ANALYZE + taskId, jsonObject.toJSONString());
        }
    }

    @Override
    public AyBehaviorTaskPlanVo sonTaskPlanDetail(Integer id) {
        //根据ID查询详情
        AyBehaviorTaskSon ayBehaviorTaskSon = this.getById(id);
        AyBehaviorTaskPlanVo ayBehaviorTaskPlanVo = BeanCopyUtils.copy(ayBehaviorTaskSon, AyBehaviorTaskPlanVo.class);
        String planInfoList = ayBehaviorTaskSon.getPlanInfoList();
        if (StringUtils.isNotBlank(planInfoList)) {
            //转为json数组
            JSONArray jsonArray = JSONArray.parseArray(ayBehaviorTaskSon.getPlanInfoList());
            if (jsonArray != null && jsonArray.size() > 0) {
                //遍历json数组，转为json获取数量并累加
                int planInfoNum = 0;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONArray array = jsonArray.getJSONArray(i);
                    if (array != null && array.size() > 0) {
                        planInfoNum += array.size();
                    }
                }
                ayBehaviorTaskPlanVo.setPlanInfoNum(planInfoNum);
            }
        }
        if (ayBehaviorTaskPlanVo.getPlanType() == 0) {
            ayBehaviorTaskPlanVo.setPlanName("周计划");
        } else if (ayBehaviorTaskPlanVo.getPlanType() == 1) {
            ayBehaviorTaskPlanVo.setPlanName("日计划");
        } else {
            ayBehaviorTaskPlanVo.setPlanName("全天");
        }
        return ayBehaviorTaskPlanVo;
    }

    @Override
    public boolean sonTaskDeletePlan(List<Integer> ids) {
        //查询子任务信息
        List<AyBehaviorTaskSon> ayBehaviorTaskSonList = this.listByIds(ids);
        //判断子任务是否存在
        if (ayBehaviorTaskSonList.isEmpty()) {
            throw new ServiceException("子任务不存在！");
        }
        //筛选出未删除的子任务
        ayBehaviorTaskSonList.removeIf(item -> item.getIsDeleted() == DeleteStatusEnum.DELETED.getValue());
        Set<Integer> setIds = ayBehaviorTaskSonList.stream().map(AyBehaviorTaskSon::getId).collect(Collectors.toSet());
        boolean isSuccess = this.update(null, Wrappers.<AyBehaviorTaskSon>lambdaUpdate()
                .set(AyBehaviorTaskSon::getPlanInfoNum, null)
                .set(AyBehaviorTaskSon::getPlanType, null)
                .set(AyBehaviorTaskSon::getPlanInfoList, null)
                .in(AyBehaviorTaskSon::getId, setIds));

        if (isSuccess) {
            //删除redis数据
            ayBehaviorTaskSonList.forEach(ayBehaviorTaskSon -> updateRedisInfo(
                    ayBehaviorTaskSon.getTaskId(),
                    null,
                    null,
                    null));
        }
        return isSuccess;
    }

    @Override
    public void sendDeleteMessage(AyBehaviorTaskSon ayBehaviorTaskSon) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OpType", "DELETE_BEHAVIOR_TASK");
        jsonObject.put("Data", ayBehaviorTaskSon.getTaskId());
        MqttOp.publish(MediaMqConstants.BEHAVIOR_TASK_TOPIC, JSON.toJSONString(jsonObject));
    }


    private void buildStopTaskSons(List<AyBehaviorTaskSon> currentTaskSons, List<AyBehaviorTaskSon> stopTaskSons) {
        //currentTaskSons构建stopTaskSons
        currentTaskSons.forEach(ayBehaviorTaskSon -> {
            AyBehaviorTaskSon stopAyBehaviorTaskSon = new AyBehaviorTaskSon();
            stopAyBehaviorTaskSon.setId(ayBehaviorTaskSon.getId());
            stopAyBehaviorTaskSon.setStatus(TaskStatusEnum.FINISHED.getValue());
            stopAyBehaviorTaskSon.setTaskId(ayBehaviorTaskSon.getTaskId());
            stopAyBehaviorTaskSon.setEndTime(LocalDateTime.now());
            stopTaskSons.add(stopAyBehaviorTaskSon);
        });
    }


    private void buildStartTaskSons(List<AyBehaviorTaskSon> currentTaskSons, List<AyBehaviorTaskSon> startTaskSons) {
        //过滤出currentTaskSons中的异常、未启动、未删除的子任务,并创建AyBehaviorTaskSon对象，添加到startTaskSons
        currentTaskSons.stream()
                .filter(ayBehaviorTaskSon ->
                        Objects.equals(ayBehaviorTaskSon.getStatus(), TaskStatusEnum.UNUSUAL.getValue()) ||
                                Objects.equals(ayBehaviorTaskSon.getStatus(), TaskStatusEnum.NOT_STARTED.getValue()))
                .forEach(ayBehaviorTaskSon -> {
                    AyBehaviorTaskSon startBehaviorTaskSon = BeanCopyUtils.copy(ayBehaviorTaskSon, AyBehaviorTaskSon.class);
//                    startBehaviorTaskSon.setStatus(TaskStatusEnum.CREATED.getValue());
                    startBehaviorTaskSon.setStatus(TaskStatusEnum.RUNING.getValue());
                    startBehaviorTaskSon.setBeginTime(LocalDateTime.now());
                    startTaskSons.add(startBehaviorTaskSon);
                });
    }


    private void buildNeedInsertAndDeleteTaskSons(List<AyBehaviorTaskSon> currentTaskSons, List<AyBehaviorTaskSon> deleteTaskSons, List<AyBehaviorTaskSon> insertTaskSons) {
        //过滤出currentTaskSons中TaskStatusEnum.FINISHED.getValue()
        List<AyBehaviorTaskSon> finishedTaskSons = currentTaskSons
                .stream()
                .filter(ayBehaviorTaskSon -> Objects.equals(ayBehaviorTaskSon.getStatus(), TaskStatusEnum.FINISHED.getValue()))
                .collect(Collectors.toList());

        //构建deleteTaskSons
        finishedTaskSons.forEach(ayBehaviorTaskSon -> {
            AyBehaviorTaskSon deleteAyBehaviorTaskSon = new AyBehaviorTaskSon();
            deleteAyBehaviorTaskSon.setId(ayBehaviorTaskSon.getId());
            deleteAyBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.DELETED.getValue());
            deleteTaskSons.add(deleteAyBehaviorTaskSon);
        });

        //构建insertTaskSons
        finishedTaskSons.forEach(ayBehaviorTaskSon -> {
            AyBehaviorTaskSon insertAyBehaviorTaskSon = new AyBehaviorTaskSon();
            insertAyBehaviorTaskSon.setBehaviorTaskId(ayBehaviorTaskSon.getBehaviorTaskId());
            insertAyBehaviorTaskSon.setBehavior(ayBehaviorTaskSon.getBehavior());
            insertAyBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.NOT_DELETED.getValue());
//            insertAyBehaviorTaskSon.setStatus(TaskStatusEnum.CREATED.getValue());
            insertAyBehaviorTaskSon.setStatus(TaskStatusEnum.RUNING.getValue());
            insertAyBehaviorTaskSon.setVideoUrl(ayBehaviorTaskSon.getVideoUrl());
            insertAyBehaviorTaskSon.setCameraName(ayBehaviorTaskSon.getCameraName());
            insertAyBehaviorTaskSon.setCameraId(ayBehaviorTaskSon.getCameraId());
            insertAyBehaviorTaskSon.setBeginTime(LocalDateTime.now());
            insertAyBehaviorTaskSon.setType(ayBehaviorTaskSon.getType());
            insertAyBehaviorTaskSon.setAlgorithmid(ayBehaviorTaskSon.getAlgorithmid());
            insertAyBehaviorTaskSon.setSubtypes(ayBehaviorTaskSon.getSubtypes());
            insertAyBehaviorTaskSon.setLicenceUsing(ayBehaviorTaskSon.getLicenceUsing());
            insertAyBehaviorTaskSon.setIsSearchStatus(ayBehaviorTaskSon.getIsSearchStatus());
            insertAyBehaviorTaskSon.setRemark(ayBehaviorTaskSon.getRemark());
            insertTaskSons.add(insertAyBehaviorTaskSon);
        });
    }


    /**
     * 添加前参数校验
     *
     * @param ayBehaviorTaskDto 参数
     * @return 校验结果
     */
    private boolean addFrontVerify(AyBehaviorTaskDto ayBehaviorTaskDto) {
        // 获取需要添加的设备信息
        List<AyCameraVo> ayCameraVos = ayBehaviorTaskDto.getAyCameraVos();
        // 校验参数
        Iterator<AyCameraVo> iterator = ayCameraVos.iterator();
        if (iterator.hasNext()) {
            //同一通道、同一事件只能有一个未删除的行为分析任务
            LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
            wrapper
                    .eq(AyBehaviorTaskSon::getCameraId, iterator.next().getCameraId())
                    .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                    .eq(AyBehaviorTaskSon::getSubtypes, ayBehaviorTaskDto.getSubtypes());
            AyBehaviorTaskSon ayBehaviorTaskSonServiceOne = this.getOne(wrapper);
            //如果ayBehaviorTaskSonServiceOne不为null,移除当前设备
            if (ayBehaviorTaskSonServiceOne != null) {
                iterator.remove();
            }
        }
        return ayCameraVos.isEmpty();
    }

}
